package drds.plus.datasource.configuration;

import drds.plus.common.utils.TStringUtil;
import drds.tools.$;

import java.text.MessageFormat;
import java.util.Map;

/**
 * 数据库连接URL生成工具类
 */
public class UrlTools {

    private static MessageFormat MYSQL_URL_FORMAT = new MessageFormat("api:mysql://{0}:{1}/{2}");

    public static String getUrl(String ip, String port, String dbName, Map<String, String> prams) {
        String conUrl = null;
        if (checkPrams(ip, port, dbName)) {
            conUrl = MYSQL_URL_FORMAT.format(new String[]{ip, port, dbName});
            if (null == prams || prams.isEmpty()) {
                prams = ConnectionPropertiesConfiguration.DEFAULT_MYSQL_CONNECTION_PROPERTIES;
            }
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : prams.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key);
                sb.append("=");
                sb.append(value);
                sb.append("&");
            }
            String pramStr = TStringUtil.substringBeforeLast(sb.toString(), "&");
            conUrl = conUrl + "?" + pramStr;
        }
        return conUrl;
    }

    private static boolean checkPrams(String ip, String port, String dbName) {
        boolean flag = false;
        if ($.isNotNullAndNotEmpty(ip) && $.isNotNullAndNotEmpty(port) && $.isNotNullAndNotEmpty(dbName)) {
            flag = true;
        }
        return flag;
    }
}
